package com.qq.client.view;

import com.qq.client.model.ClientConServerThread;
import com.qq.client.model.ManageClientConServerThread;
import com.qq.common.Message;
import com.qq.common.MessageType;
import javafx.util.converter.DateStringConverter;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;

/**
 * @author weiBin
 * @date 2019/1/9
 */
public class QqChat extends JFrame implements ActionListener {
    JTextArea jta;
    JPanel jpl1;
    JTextField jtf;
    JButton jbt1;
    String ownerNo;
    String friendNo ;
    public QqChat(String ownerNo, String friendNo) {
        this.ownerNo = ownerNo;
        this.friendNo = friendNo;
        jta = new JTextArea();
        jpl1 = new JPanel();
        jtf = new JTextField(15);
        jbt1 = new JButton("发送");
        jbt1.addActionListener(this);
        jpl1.add(jtf);
        jpl1.add(jbt1);
        jta.setEnabled(false);
        this.add(jta, "Center");
        this.add(jpl1, "South");
        this.setSize(300, 200);
        this.setVisible(true);
        this.setIconImage(new ImageIcon(QqChat.class.getResource("/image/qq.gif")).getImage());
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        this.setTitle("正在与" + friendNo + "聊天");
    }

    //写一个方法，让它显示消息
    public void showMessage(Message m) {
        String info = m.getSender() + " 对 " + m.getGetter() + " 说:" + m.getCon() + "\r\n";
        this.jta.append(info);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String message = jtf.getText();
        if (e.getSource() == jbt1 && message.length() > 0) {
            this.jta.append(ownerNo+" 对 "+friendNo+"说：" + message + "\r\n");
            ClientConServerThread clientConServerThread = ManageClientConServerThread.getClientConServerThread(ownerNo);
            try {
                ObjectOutputStream oot = new ObjectOutputStream(clientConServerThread.getSocket().getOutputStream());
                Message m = new Message();
                m.setMesType(MessageType.message_comm_mes);
                m.setCon(message);
                m.setGetter(friendNo);
                m.setSender(ownerNo);
                m.setSendTime(new DateStringConverter().toString(new Date()));
                oot.writeObject(m);
                jtf.setText("");
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
